﻿using Microsoft.AspNetCore.Http;

namespace FDSimpleModelGenerator.Common.Mvc
{
    /// <summary>
    /// Ip工具
    /// </summary>
    public static class IpUtil
    {
        /// <summary>
        /// 获取Ip
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public static string GetRequestIp(HttpContext context)
        {
            string srcIp = context.Request.Headers["Cdn-Src-Ip"];
            if (!string.IsNullOrWhiteSpace(srcIp))
            {
                return srcIp;
            }

            srcIp = context.Request.Headers["X-Real-IP"];
            if (!string.IsNullOrWhiteSpace(srcIp))
            {
                return srcIp;
            }
            srcIp = context.Request.Headers["X-Forwarded-For"];
            if (!string.IsNullOrWhiteSpace(srcIp))
            {
                return srcIp;
            }
            srcIp = context.Connection.RemoteIpAddress.MapToIPv4().ToString();
            return srcIp;
        }

        /// <summary>
        /// 请求的Ip
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public static string RequestIp(this HttpContext context)
        {
            return GetRequestIp(context);
        }
    }
}
